 
package com.zdkj.subway.st.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.fill.FillConfig;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zdkj.common.core.exceltools.ExcelUtil;
import com.zdkj.common.core.exceltools.IExcelParser;
import com.zdkj.common.core.exceltools.MultipartFileToFile;
import com.zdkj.common.core.exceltools.impl.CommonExcelParse;
import com.zdkj.common.data.mybatis.wrapper.CustomQueryWrapper;
import com.zdkj.subway.st.entity.SwTkOfficialProduction;
import com.zdkj.subway.st.mapper.SwTkOfficialProductionMapper;
import com.zdkj.subway.st.service.SwTkOfficialProductionService;
import com.zdkj.subway.st.util.LocalDateConverter;
import com.zdkj.subway.st.util.LocalDateTimeConverter;
import lombok.AllArgsConstructor;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.List;

/**
 * 公务票生产
 *
 * @author chenbo
 * @date 2020-06-10 10:21:03
 */
@Service
@AllArgsConstructor
public class SwTkOfficialProductionServiceImpl extends ServiceImpl<SwTkOfficialProductionMapper, SwTkOfficialProduction> implements SwTkOfficialProductionService {
    private static final Logger LOGGER = LoggerFactory.getLogger(SwTkOfficialProductionServiceImpl.class);
    private final SwTkOfficialProductionMapper swTkOfficialProductionMapper;
    @Override
    public Page pageExport(Page page, CustomQueryWrapper a) {
        return page.setRecords(swTkOfficialProductionMapper.pageExport(page,a));
    }

    @Override
    public Boolean saveBatchWithExcel(File excelFile) throws Exception {
        Workbook workbook = ExcelUtil.chooseWorkbook(excelFile);
        Sheet sheet=workbook.getSheetAt(0);
        IExcelParser excelParser=new CommonExcelParse();
        List<SwTkOfficialProduction> swTkOfficialProductions = excelParser.parse(sheet,new SwTkOfficialProduction());
        if(CollectionUtil.isNotEmpty(swTkOfficialProductions)){
            //刪除緩存文件
            MultipartFileToFile.delteTempFile(excelFile);
            return this.saveBatch(swTkOfficialProductions);
        }else{
            return false;
        }
    }

    @Override
    public void export(SwTkOfficialProduction swTkOfficialProduction, HttpServletResponse response) {
        String startDate = null;
        String endDate = null;
        List<String> dates1 = swTkOfficialProduction.getDates1();
        if(CollectionUtil.isNotEmpty(dates1)){
            startDate = dates1.get(0);
            endDate = dates1.get(1);
        }
        List<SwTkOfficialProduction> records = this.baseMapper.getList(startDate,endDate,swTkOfficialProduction);
        InputStream excelTemplateIs = null;
        try {
            response.reset(); // 非常重要
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            final String fileName = URLEncoder.encode("公务票生产申请", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + System.currentTimeMillis() + ".xlsx");

            // 模板注意 用{} 来表示你要用的变量 如果本来就有"{","}" 特殊字符 用"\{","\}"代替
            // {} 代表普通变量 {.} 代表是list的变量
            //模版 TODO
            excelTemplateIs = this.getClass().getResourceAsStream("/static/excel/template/export/SwTkOfficialProductionExcelTemplate.xlsx");
            WriteSheet writeSheet = EasyExcel.writerSheet("公务票生产申请").build();
            // 这里注意 入参用了forceNewRow 代表在写入list的时候不管list下面有没有空行 都会创建一行，然后下面的数据往后移动。默认 是false，会直接使用下一行，如果没有则创建。
            // forceNewRow 如果设置了true,有个缺点 就是他会把所有的数据都放到内存了，所以慎用
            // 简单的说 如果你的模板有list,且list不是最后一行，下面还有数据需要填充 就必须设置 forceNewRow=true 但是这个就会把所有数据放到内存 会很耗内存
            // 如果数据量大 list不是最后一行 参照另一个
            ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream()).registerConverter(new LocalDateTimeConverter()).registerConverter(new LocalDateConverter()).withTemplate(excelTemplateIs).build();
            FillConfig fillConfig = FillConfig.builder().forceNewRow(Boolean.FALSE).build();
            excelWriter.fill(records, fillConfig, writeSheet);
            excelWriter.finish();

        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("导出失败");
        } finally {
            if(excelTemplateIs != null){
                try {
                    excelTemplateIs.close();
                } catch (IOException ioe) {
                    ioe.printStackTrace();
                }
            }
        }
    }
}
